import superManager from "./superManager";
import { modules, services } from "../gameEngine";
import { VIBRATE_TYPE } from "../services/miniGameContent/miniApp";
import mainRoot from "../../Game/MainRoot";

//
export interface SoundLocal {
    sound: boolean;
    vibrate: boolean;
}

export interface SoundBundleMap {
    [name: string]: cc.AssetManager.Bundle;
}

export const SOUND_LOCAL_KEY: string = 'sound-manager-key';

export default class soundManager extends superManager {

    protected className: string = '声音管理';

    protected soundBundleMap: SoundBundleMap = {};

    constructor() {
        super();
    }

    //level1/normal_speak3
    getSoundBundle(name: string) {
        let index = name.indexOf("/");
        let str = name.slice(0, index);
        return this.soundBundleMap[str];
    }

    addOneSoundBundle(name:string,bundle:cc.AssetManager.Bundle){
        this.soundBundleMap[name] = bundle;
    }

    loadSoundBundle(level?: string, gameAloneBundle: string = '') {
        //加载独立分包
        if (gameAloneBundle) {
            return new Promise<void>(resolve => {
                cc.assetManager.loadBundle(gameAloneBundle, null, (err, bundle: cc.AssetManager.Bundle) => {
                    if (err) {
                        resolve();
                        return;
                    }
                    this.soundBundleMap[gameAloneBundle] = bundle;
                    resolve();
                });
            });
        }
        return new Promise<void>(resolve => {
            if (level != null) {
                cc.assetManager.loadBundle(level, null, (err, bundle: cc.AssetManager.Bundle) => {
                    if (err) {
                        console.log("加载音效失败");
                        resolve();
                        return;
                    }
                    this.soundBundleMap[level] = bundle;
                    resolve();
                });
            } else {
                cc.assetManager.loadBundle(`mainSound`, null, (err, bundle: cc.AssetManager.Bundle) => {
                    if (err) {
                        console.log("加载音效失败");
                        resolve();
                        return;
                    }
                    this.soundBundleMap[`mainSound`] = bundle;
                    // this.playMusic("mainSound/dating");
                    resolve();
                });
            }
        });
    }

    async loadManager(): Promise<void> {
        await super.loadManager();
        //
        this.onReadSetting();
        //
        return Promise.resolve();
    }

    public set Volume(value) {
        if (!this.isSoundEnabled()) { return; }
        cc.audioEngine.setMusicVolume(value);
    }
    public get Volume() {
        return cc.audioEngine.getMusicVolume();
    }

    //
    readonly soundResPath = "";

    //声音开关
    private m_soundEnabled: boolean = true;
    //振动开头
    private m_vibrateEnabled: boolean = true;

    //获取声音的开关
    isSoundEnabled() {
        return this.m_soundEnabled;
    }

    isVibrateEnabled() {
        return this.m_vibrateEnabled;
    }

    setVibrateEnabled(enabled: boolean) {
        this.m_vibrateEnabled = enabled;
        this.onSetWriteSetting();
    }

    //设置声音的开关
    setSoundEnabled(enabled: boolean) {
        this.m_soundEnabled = enabled;
        if (!this.isSoundEnabled()) {
            this.stopMusic();
        }
        this.onSetWriteSetting();
    }

    private onSetWriteSetting() {
        let obj: SoundLocal = {
            sound: this.m_soundEnabled,
            vibrate: this.m_vibrateEnabled,
        }
        services().localStorageSrv.setStorage(SOUND_LOCAL_KEY, JSON.stringify(obj));
    }

    private onReadSetting() {
        let data = services().localStorageSrv.getStorage(SOUND_LOCAL_KEY);
        if (data) {
            let obj: SoundLocal = JSON.parse(data);
            this.m_soundEnabled = obj.sound;
            this.m_vibrateEnabled = obj.vibrate;
        }
    }

    //播放振动
    playVibrate() {
        if (this.isVibrateEnabled()) {
            services().miniGameSrv.getAppApiInstance().vibrate(VIBRATE_TYPE.SHORT);
        }
    }

    /**
     * 播放背景音
     * gameBundle/preload/sound/aaa.mp3  ryw_playBGM("aaa")
     * @param name 具体名字 不带后缀.mp3
     */
    playMusic(name: string) {
        if (!this.isSoundEnabled())
            return;
        let url = this.getSoundUrl(name);
        //播放背景音乐
        this.getSoundBundle(name)?.load(url, cc.AudioClip, function (err, clip: cc.AudioClip) {
            if (err) {
                // cc.error(err);
                return;
            }
            cc.audioEngine.playMusic(clip, true);
        });
    }

    /**
     * 停止播放背景音乐
     */
    stopMusic() {
        cc.audioEngine.stopMusic();
    }

    /**
     * 播放音效
     * @param name 具体名字 不带后缀.mp3
     * @returns 异步返回 播放的ID soundId
     */
    async playSound(name: string, overCb?: () => void): Promise<number> {
        return new Promise(resolve => {
            if (!this.isSoundEnabled()) {
                overCb&&overCb();
                return resolve(null);
            }
            if(!name){
                overCb&&overCb();
                return resolve(null);
            }
            let url = this.getSoundUrl(name);
            // console.log(url,"urllllll",name,this.soundBundleMap)
            //
            this.getSoundBundle(name)?.load(url, cc.AudioClip, function (err, clip: cc.AudioClip) {
                if (err) {
                    //拿游戏资源包
                    // mainRoot.GetBundle(mainRoot.curLoadBundleName).
                    // load(`sounds/${name}`, cc.AudioClip, function (err, clip: cc.AudioClip) {
                    if (err) {
                        console.info("存在音频问题")
                        // cc.error(err);
                        return resolve(null);
                    }
                } else {
                    try{
                        if (clip) {
                            let audioId = cc.audioEngine.play(clip, false, 1);
                            if(audioId==-1)overCb&&overCb()
                            overCb && cc.audioEngine.setFinishCallback(audioId, overCb);
                            resolve(audioId);
                        }else{
                            overCb&&overCb();
                            resolve(null)
                        }
                    }catch(e){
                        console.warn('#89警告 存在音频问题', url);
                        overCb&&overCb();
                        resolve(null)
                    }
                }
            });
        })
    }

    /**
     * 停止音效
     * @param soundId
     */
    stopSound(audioId: number) {
        cc.audioEngine.stop(audioId);
    }

    /**
     * 暂停音效
     * @param soundId
     */
    pauseSound(audioId: number) {
        cc.audioEngine.pause(audioId);
    }

    stopAllSound() {
        cc.audioEngine.stopAll();
    }

    stopAllEffect() {
        cc.audioEngine.stopAllEffects();
    }

    /**
     * 恢复音效
     * @param soundId
     */
    resumeSound(audioId: number) {
        cc.audioEngine.resume(audioId);
    }

    getSoundUrl(name: string): string {
        let url = this.soundResPath + name;
        let index = name.indexOf("/");
        let str = name.substring(index + 1);
        return str;
    }
}

























